<?php
/**
 * Category
 * Created by Veyron
 * motto:现在的拼搏 为了更好的明天
 * day:  2020/2/7
 * Time: 15:51
 */

namespace app\common\business;

use app\common\model\mysql\Category as CategoryModel;
use think\Exception;

class Category extends BusBase
{
    public $model = null;
    public function __construct()
    {
        $this->model = new CategoryModel();
    }

    /**
     * 获取正常的分类
     * @return array
     */
    public function getNormalCategorys(){
        $field = "id,name,pid";
        $categorys = $this->model->getNormalCategorys($field);
        if(!$categorys){
           return [];
        }
        $categorys = $categorys->toArray();
        return $categorys;
    }

    /**
     * 获取正常的全部分类
     * @return array
     */
    public function getNormalAllCategorys(){
        $field = "id as category_id,name,pid";
        $categorys = $this->model->getNormalCategorys($field);
        if(!$categorys){
            return [];
        }
        $categorys = $categorys->toArray();
        return $categorys;
    }
    /**
     * 获取分类列表
     * @param $data
     * @param $num
     * @return array
     */
    public function getLists($data,$num){
        $lists = $this->model->getLists($data,$num);
        if(!$lists){
           return [];
        }
        $result = $lists->toArray();
        $result['render'] = $lists->render();
        /** 获取每个顶级分类的子分类数 */
        //思路 第一步 拿到列表中的id,第二步 in mysql 求 count ,第三步 把 count 填充到 列表页中
        $pids = array_column($result['data'],'id');
        if($pids){
            $idCountResult = $this->model->getChildCountInPids(['pid'=>$pids]);
            $idCountResult = $idCountResult->toArray(); //没有内容 返回空数组
            $idCounts = [];
            foreach ($idCountResult as $countResult){
                $idCounts[$countResult['pid']] = $countResult['count'];
            }
        }
        if($result['data']){
            foreach ($result['data'] as $k=>$item) {
                // $a ?? 0 等同于 isset($a)?$a:0
                $result['data'][$k]['childCount'] = $idCounts[$item['id']] ?? 0;
            }
        }
        /** 获取子分类数end */
        return $result;
    }



    /**
     * 修改排序 listorder
     * @param $id
     * @param $listorder
     * @return array|bool|\think\Model|null
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function listorder($id,$listorder){
        //查询记录是否存在
        $res = $this->getById($id);
        if(!$res){
            throw new Exception('不存在该条记录');
        }
        $data = [
            'listorder' => $listorder
        ];
        try{
            $res = $this->model->updateById($id,$data);
        }catch (\Exception $e){
            //记录日志
            return false;
        }
        return $res;
    }


    /**
     * 编辑分类
     * @param $id
     * @param $data
     * @return bool
     * @throws Exception
     */
    public function update($id,$data){
        $data['status'] = config('status.mysql.table_normal');
        try{
           $result = $this->model->where('id',$id)->save($data);
        }catch (\Exception $e){
            throw new Exception('服务器内部异常');
        }

        return $result;
    }

    /**
     * 获取全部上级分类 id（暂时使用循环，后期尽量改成一条SQL执行）
     * @param $id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getAllUpPids($id){
        $pids = [];
        while(true){
            $pid =  $this->model->field(['id','pid','name'])->find($id);
            if(!$pid){
                break;
            }
            $id = $pid->toArray();

            $pids[] = $id;
            if ($id['pid'] == 0){
                break;
            }
        }
        $result['data']  = array_reverse($pids);
        $result['count'] = count($pids);
        return $result;
    }

    /**
     * 根据pid获取普通分类
     * @param int $pid
     * @param string $field
     * @return array|\think\Collection
     */
    public function getNormalByPid($pid = 0, $field = 'id,name,pid'){
        try {
            $result = $this->model->getNormalByPid($pid, $field);
        }catch (\Exception $e){
            //记录日志
            return [];
        }
        $result = $result->toArray();
        return $result;
    }

    /**
     * 根据id批量获正常父分类信息
     * @param $categoryIds
     * @param bool $field
     * @return \think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getNormalCategoryInPidsByIds($categoryIds, $field =  true, $in = 'id'){

        try {
            $result = $this->model->getNormalCategorysInPidsById($categoryIds, $field, $in);
        }catch (\Exception $e){
            return [];
        }

        return $result->toArray();
    }
    public function getCateListByPid($id){
        //获取分类列表
        $list = $this->getNormalByPid($id);
        $result = [];
        if(!empty($list)){
            $result['id'] = $list[0]['id'];
        }else{
            $result['id'] = '';
        }
        $result['list'] = $list;
        return $result;
    }
}
